package com.army.study.provider;


import com.army.study.ResourceTable;
import com.army.study.util.ToastUtil;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.data.distributed.common.KvManagerConfig;
import ohos.data.distributed.common.KvManagerFactory;
import ohos.distributedschedule.interwork.DeviceInfo;
import ohos.distributedschedule.interwork.DeviceManager;
import ohos.global.resource.Element;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;
import java.util.List;

/**
 * 信件适配器
 */
public class LetterProvider extends CommonItemProvider<String> {

    public LetterProvider(Context mContext, List<String> listData) {
        super(mContext, listData);
        mContext = mContext;
    }

    @Override
    public int getXmlId() {
        return ResourceTable.Layout_dialog_item;
    }

    @Override
    public void convert(CommonComponentHolder holder, int position, String data) {
        Text textFileName = holder.getComponent(ResourceTable.Id_text_item_txt_fileName);
        Text textDeviceType = holder.getComponent(ResourceTable.Id_text_item_txt_deviceType);

        // 设备ID
        String deviceID = KvManagerFactory.getInstance().createKvManager(new KvManagerConfig(mContext))
                .getLocalDeviceInfo().getId();
        // 截取需要显示的文件名
        String showFileName = data.substring(data.indexOf("-")+1);

        textFileName.setText(showFileName);

        // 查询分布式网络中所有在线设备（不包括本地设备）的信息。
        List<DeviceInfo> deviceList = DeviceManager.getDeviceList(DeviceInfo.FLAG_GET_ONLINE_DEVICE);

        // 没有设备，不显示（本地和远程）
        if(deviceList.isEmpty()){
            textDeviceType.setVisibility(Component.HIDE);
        }else {
            textDeviceType.setVisibility(Component.VISIBLE);
            if(data.contains(deviceID)){
                textDeviceType.setText("本地端");
                try {
                   Element element = mContext.getResourceManager().getElement(ResourceTable.Color_device_local);
                   textDeviceType.setTextColor(new Color(element.getColor()));
                } catch (IOException | NotExistException | WrongTypeException e) {
                    e.printStackTrace();
                }
            }else{
                textDeviceType.setText("远程端");
                try {
                    Element element = mContext.getResourceManager().getElement(ResourceTable.Color_device_remote);
                    textDeviceType.setTextColor(new Color(element.getColor()));
                } catch (IOException | NotExistException | WrongTypeException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
